//
//  ZZOAuthViewController.swift
//  SinaWeibo
//
//  Created by QUAN on 15/11/10.
//  Copyright © 2015年 QUAN. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class ZZOAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    //关闭页面
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充
    @objc private func fullAccount() {
        let jsString = "document.getElementById('userId').value = '1035610761@qq.com' , document.getElementById('passwd').value = 'z19961124';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //添加按钮
        setUpUi()
        //跳转到微博登录界面
        loadOauthPage()
        
    }

    func setUpUi() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    //跳到微博登录界面
    func loadOauthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }
}

//分出来实现web的代理
extension ZZOAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        
        guard let query = request.URL?.query else {
            return false
        }
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        
        ZZUserAccountViewModel().loadAccessToken(code) { (error) -> () in
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                //实现通知, 跳转到欢迎页面
                NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "Welcome")
            })
        }
        
        print(query)
        
        return false
    }

}
